<template>
  <el-dialog
    title="用户注册"
    :visible.sync="IsShow"
    width="600px"
    :show-close="false"
    class="register"
  >
    <template #title>
      <div class="title">用户注册</div>
    </template>
    <span slot="footer">
      <el-button @click="IsShow = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
    <el-form :model="form" ref="form" :rules="rules" label-width="100px">
      <el-form-item label="头像" class="upload-avatar" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="BaseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="form.avatar"
            :src="BaseUrl + '/' + form.avatar"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img class="w143" :src="code" @click="ClickCode" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="getrcode" :disabled="rcodeTime != 5"
              >获取用户验证码<span v-if="rcodeTime != 5"
                >({{ rcodeTime }}s)</span
              ></el-button
            >
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { Getcode, ToRetister } from '@/api/register.js'
export default {
  data () {
    return {
      IsShow: false,
      BaseUrl: process.env.VUE_APP_URL,
      code: `${process.env.VUE_APP_URL}/captcha?type=sendsms`,
      rcodeTime: 5,
      form: {
        avatar: '', //头像地址
        username: '', //是	string	用户名
        phone: '', //是	string	手机号
        email: '', //是	string	邮箱
        password: '', //是	string	密码
        code: '',
        rcode: '' //是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: '请输入头像', trigger: 'change' }], //头像地址
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' }
        ], //是	string	用户名
        phone: [{ required: true, message: '请输入手机号', trigger: 'change' }], //是	string	手机号
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let res = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (res.test(value)) {
                callback()
              } else {
                callback('请输入正确邮箱')
              }
            },
            trigger: 'change'
          }
        ], //是	string	邮箱
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ], //是	string	密码
        code: [{ required: true, message: '请输入图形码', trigger: 'change' }],
        rcode: [{ required: true, message: '请输入验证码', trigger: 'change' }] //是	string	验证码
      }
    }
  },
  watch: {
    IsShow (newval) {
      if (newval == false) {
        this.$refs.form.resetFields()
      }
    }
  },
  methods: {
    handleAvatarSuccess (res) {
      console.log(res)
      this.form.avatar = res.data.file_path
      this.$refs.form.validateField(['avatar'])
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submit () {
      this.$refs.form.validate(res => {
        if (res) {
          ToRetister(this.form)
            .then(res => {
              console.log(res)

              this.$message.success('注册成功')
              this.IsShow = false
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          this.$message.error('验证失败!')
        }
        console.log(this.code)
        console.log(this.BaseUrl)
      })
    },
    ClickCode () {
      this.code = `${
        process.env.VUE_APP_URL
      }/captcha?type=sendsms&t=${Math.random()}`
    },
    getrcode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], error => {
        console.log('手机效验', error)

        if (error == '') {
          num++
        }
        if (num == 2) {
          this.rcodeTime--
          let _time = setInterval(() => {
            this.rcodeTime--
            if (this.rcodeTime <= 0) {
              clearInterval(_time)
              this.rcodeTime = 5
            }
          }, 1000)
          Getcode({ code: this.form.code, phone: this.form.phone })
            // this.$axios({
            //   url: '/sendsms',
            //   method: 'post',
            //   data: {
            //     code: this.form.code,
            //     phone: this.form.phone
            //   }
            // })
            .then(res => {
              this.$message.success(res.data.data.captcha + '')
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
    }
  }
}
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    text-align: center;
    color: #fff;
    background: linear-gradient(to left, #01c5fa, #1394fa);
  }
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__footer {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-avatar {
    text-align: center;
  }
  .w143 {
    width: 143px;
    height: 41px;
  }
}
</style>
